<?php

namespace App\Http\Controllers\Home\Article;

use App\Library\Upload;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Mockery\CountValidator\Exception;

class ArticleController extends Controller {

    public function gets(Request $request) {
        $data   = $request->input();
        $data   = [
            'size' => isset($data['size']) ? intval($data['size']) : '',
            'page' => isset($data['page']) ? intval($data['page']) : '',
        ];
        $offset = (intval($data['page']) - 1) * intval($data['size']);

        $ret = DB::table('article')
                 ->leftJoin('category', 'article.category_id', '=', 'category.id')
                 ->leftJoin('article_img', 'article.id', '=', 'article_img.article_id')
                 ->select('article.id', 'article.auth', 'article.title', 'article.intro', 'article_img.img_url', 'category.name', 'article.status', 'article.create_at', 'article.update_at')
                 ->skip($offset)
                 ->take($data['size'])
                 ->get()
                 ->toArray();
        if(isset($ret[0]->auth)) {
            array_map(function ($v) {
                $v->create_at=date('Y - m - d', strtotime($v->create_at));
            }, $ret);
            return $this->ajax(true, $ret);
        }
        return $this->ajax(false, '获取失败');
    }

    public function hots() {
        $ret = DB::table('article')->orderBy('click', 'desc')->get()->toArray();
        if(is_array($ret)) {
            return $this->ajax(true, $ret);
        }
        return $this->ajax(true, '获取失败');
    }

    public function count() {
        $count = DB::table('article')->count();
        return $this->ajax(true, $count);
    }

    public function get(Request $request) {
        $id = $request->input('id');
        if(!isset($id) || !is_numeric($id)) {
            return $this->ajax(false, '文章获取错误');
        }
        $ret = DB::table('article')
                 ->leftJoin('category', 'article.category_id', '=', 'category.id')
                 ->leftJoin('article_img', 'article.id', '=', 'article_img.article_id')
                 ->select('article.id', 'article.auth','article.click',  'article.title', 'article.content', 'article.intro', 'article_img.img_url as img', 'category.name as category_name', 'category.id as category_id', 'article.status', 'article.create_at', 'article.update_at')
                 ->where('article.id', '=', $id)
                 ->first();
        if($ret !== null) {
            return $this->ajax(true, $ret);
        }
        return $this->ajax(false, '文章获取错误');
    }

}
